<template>
  <div>
    <div class="mytest search-input" >
      <!-- 搜索指定学校 -->
      <div v-if="this.roleName != 'schoolAdmin'">
        <el-input
          type="text"
          placeholder="请输入要查询学校ID"
          class="account-search"
          id="account-search-border"
          @keyup.enter.native="searchId"
          @blur="searchId"
          v-model="input.id"
          clearable
        >
          <span 
            slot="prefix" 
            class="el-icon-search account-search-icon"
          ></span>
        </el-input>
        <el-input
          type="text"
          placeholder="查询学校名称"
          class="account-search"
          id="account-search-border"
          @keyup.enter.native="searchName"
          @blur="searchName"
          v-model="input.name"
          clearable
        >
          <span 
            slot="prefix" 
            class="el-icon-search account-search-icon"
          ></span>
        </el-input>
        <!-- 添加学校 -->
        <el-button
          size="medium"
          icon="el-icon-plus"
          class="add-button"
          @click="add"
        >新增学校</el-button>
      </div>
      <!-- 判断是新增还是修改信息 -->
      <el-dialog
        :title="isAdd ? '新增' : '编辑'"
        :visible="dialogVisible"
        @update:visible="dialogCancel"
      > 
        <!-- 输出信息框 -->
        <el-form 
          ref="ruleForm" 
          :model="formData" 
          class="info-change"
          label-width="100px"
        >
        <!-- :label-position= "left"-->
          <template v-for="(item, index) of columnList">
            <el-form-item
              v-if="item.edit"
              :key="index"
              :label="item.label + ':'"
              :prop="item.prop"
              :rules="item.rules"
            >
              <el-input
                v-if="item.type == 'text'"
                v-model="formData[item.prop]"
                :disabled="`${roleName}` == 'schoolAdmin'"
              ></el-input>
            </el-form-item>
          </template>
          <!--elementui的上传图片的upload组件-->
          <el-form-item 
            label= "背景图片"
            required
          >
            <el-upload 
              action=""
              :limit=1
              :auto-upload= false
              :on-change="onchange"
              :on-remove="handleRemove"
              accept="image/jpeg,image/jpg,image/png"
              :file-list="fileList"
              list-type="picture"
            >
              <el-button v-if="uploadVisible" size="mini" type="primary">{{isAdd?"点击上传":"更换背景"}}</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogCancel" class="cancel-button">取 消</el-button>
          <el-button 
            :loading="submitLoading"
            @click="submit"
            class="confirm-button"
          >确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <!-- 数据展示 -->
      <el-main>
        <el-table 
          :data="tableData" 
          v-loading="tableLoading"
          stripe
        >
          <template v-for="item in columnList">
            <!-- 输出需要的信息栏 -->
            <el-table-column
              :key="item.prop"
              :prop="item.prop"
              :label="item.label"
            ></el-table-column>
          </template>

          <el-table-column label="操作">
            <template v-slot="{ row }">
              <!-- 编辑信息 -->
              <el-button 
                size="small" 
                @click="edit(row)"
                icon="el-icon-edit-outline"
                class="btn_primary"
              >编辑</el-button>
              <!-- 删除账号 -->
              <el-button
                :loading="row.removelaoding"
                slot="reference"
                size="small"
                icon="el-icon-delete"
                @click="removeConfirm(row)"
                class="btn_danger"
                :disabled="`${roleName}` == 'schoolAdmin'"
              >删除</el-button>
            </template>
          </el-table-column>
          <el-table-column>
          </el-table-column>
        </el-table>

        <!-- 数据展示方式 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 40]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize"
          class="change-page"
        ></el-pagination>
      </el-main>
    </div>
  </div>
</template>
<script>
const columnList = [
  {
    label: "学校Id",
    type: "text",
    prop: "id",
    //是否可以编辑渲染表单
    edit: false,
  },
  {
    label: "学校名称",
    type: "text",
    prop: "schoolName",
    edit: true,
    rules: [{ required: true, message: "请输入学校名称", trigger: "blur" }],
  },{},
  {
    label: "学校公邮",
    type: "text",
    prop: "email",
    edit: true,
    rules: [{ required: true, message: "请输入学校公邮", trigger: "blur" },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
    ],
  },
];
import {
  addSchool,
  getSchools,
  update,
  deleteSchool,
  findBySchoolId,
  findBySchoolName,
  uploadbg
} from "@/api/school";
export default {
  data() {
    return {
      currentPage: 1,
      pagesize: 10,
      totalSize: 0,
      tableData: [],
      removeLoading: false,
      dialogVisible: false,
      userInfo: {},
      tableLoading: false,
      formLabelWidth: "120px",
      formData: {},
      isAdd: true,
      submitLoading: false,
      columnList,
      input:{},
      fileList:[],
      file:'',
      uploadVisible:true,
      roleName:null
    };
  },
  created() {
    // this.getTableData();
    //获取当前用户信息
    this.userInfo = JSON.parse(localStorage.getItem("user"));
    this.roleName =this.userInfo.roleName;
    console.log(this.userInfo);
    if(this.roleName=='schoolAdmin'){
      this.input.id=this.userInfo.schoolId;
      this.searchId();
    }
    else this.getTableData();
  },
  methods: {
    getTableData() {
      this.tableLoading = true;
      getSchools({
        pageNum: this.currentPage,
        pageSize: this.pagesize,
      })
        .then((res) => {
          //得到所有学校的列表
          // console.log(res.data);
          res.data.forEach((element) => {
            element.removeLoading = false;
          });
          this.tableData = res.data;
          this.totalSize = res.total;
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    //触发添加学校事件
    add() {
      this.dialogVisible = true;
      //this.$refs.ruleForm.clearValidate();
      this.isAdd = true;
    },
    //触发编辑教师信息事件
    edit(data) {
      this.formData = {...data};
      this.isAdd = false;
      //this.$refs.ruleForm.clearValidate();
      this.dialogVisible = true;
    },
    //取消消息框编辑模式
    dialogCancel() {
      this.formData = {};
      this.dialogVisible = false;
      this.fileList=[];
      this.uploadVisible=true;
    },
    //搜索指定学校
    searchId() {
      if(!this.input.id){
        this.getTableData();
        return ;
      }
      this.tableLoading = true;
      findBySchoolId(this.input.id)
        .then((res) => {
          // console.log(res);
          this.tableData = [];
          this.tableData[0] = res.data;
          this.totalSize=1;
        })
        .catch((err) => {
          this.tableData = [];
          this.totalSize = 0;
          // console.log(err);
        })
        .finally(() => {
          this.tableLoading = false;
          this.message=false;
        });
    },
    searchName() {
      if(!this.input.name){
        this.getTableData();
        return ;
      }
      this.tableLoading = true;
      let obj={
        schoolNameKey:this.input.name,
        pageNum: this.currentPage,
        pageSize: this.pagesize
      }
      findBySchoolName(obj)
        .then((res) => {
          console.log(res);
          this.tableData = [];
          if(res.data){
            this.tableData = res.data;
            this.totalSize=res.total;
          }
        })
        .catch(() => {
          this.tableData = [];
          this.totalSize = 0;
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },

    //确认是否删除
    removeConfirm(row) {
      this.$confirm( '删除后不可恢复','是否删除学校？', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        center: true
      }).then(() => {
        this.remove(row);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //删除账号
    remove(row) {
      row.removeLoading = true;
      deleteSchool(row.id)
        .then((res) => {
          this.$message.success("删除成功");
        })
        .finally(() => {
          row.removeLoading = false;
          this.getTableData();
        });
    },
    cancel(){
      this.dialogVisible = false;
      this.formData={};
    },
    //提交新增或修改信息
    submit() {
      this.$refs.ruleForm
        .validate((valid) => {
          if (valid) {
            this.submitLoading = true;
            if (this.isAdd) {
              if(this.uploadVisible){
                this.submitLoading = false;
                this.$message('请输入背景图片');
                return;
              }
              
              addSchool(this.formData)
                .then((res) => {
                  var bg={};
                  bg=new FormData();
                  bg.append("file",this.file);
                  bg.append("school_id",res.data);
                  uploadbg(bg);
                  this.$message.success("新增成功");
                  this.getTableData();
                })
                .finally(() => {
                  this.submitLoading = false;
                  this.cancel();
                  this.fileList=[];
                  this.uploadVisible=true;
                });
            } else {
              delete this.formData.createdTime;
              delete this.formData.updatedTime;
              delete this.formData.removeLoading;
              //该功能还不能用
              if(!this.uploadVisible){
                var bg={},
                bg=new FormData();
                bg.append("file",this.file);
                bg.append("school_id",this.formData.id);
                console.log(bg);
                uploadbg(bg);
              }
              update(this.formData)
                .then((res) => {
                  // console.log(res);
                  this.$message.success("修改成功");
                  if(this.roleName=='schoolAdmin'){
                    this.input.id=this.userInfo.schoolId;
                    this.searchId();
                  }
                  else this.getTableData();
                })
                .finally(() => {
                  this.submitLoading = false;
                  this.cancel();
                  this.fileList=[];
                  this.uploadVisible=true;
                });
            }
          }
        })
    },
    onchange(file){
      this.file=file.raw;
      this.uploadVisible=false;
    },
    handleRemove(){
      this.file='';
      this.fileList=[];
      this.uploadVisible=true;
    },
    handleSizeChange(size) {
      this.pagesize = size;
      //每页下拉显示数据
      if(this.roleName=='schoolAdmin'){
        this.input.id=this.userInfo.schoolId;
        this.searchId();
      }
      else {
        if(this.input.id){
          this.searchId();
          return;
        }
        if(this.input.name){
          this.searchName();
          return;
        }
        this.getTableData();
      }
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      if(this.roleName=='schoolAdmin'){
        this.input.id=this.userInfo.schoolId;
        this.searchId();
      }
      else {
        if(this.input.id){
          this.searchId();
          return;
        }
        if(this.input.name){
          this.searchName();
          return;
        }
        this.getTableData();
      }
    },
  },
};
</script>
<style scoped>
.title {
  font-size: 32px;
  color: #409eff;
  margin-bottom: 30px;
  font-weight: bold;
}
</style>
<style type="text/css">
.mytest {
  height: 42px;
  flex-direction: row;
  justify-content: flex-start;
  display: -webkit-box;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  flex-direction: row;
  -webkit-box-pack: start;
  -ms-flex-pack: start;
  justify-content: flex-start;
  flex-wrap: nowrap;
}
.el-dialog__header{
  background-color:#5b8bff;
  text-align: left;
  height: 20px;
}
.el-dialog__title {
  color: #f4f4f5;
  font-size: 18px;
}
.el-dialog__headerbtn .el-dialog__close {
  color: #f4f4f5;
}
.info-change{
  padding: 3% 6%;
  border-bottom:2px solid #c0c4cc8f;
}
.el-form-item__label{
  text-align: center;
}
.el-dialog__footer{
  text-align: center;
}
.el-message-box__btns .el-button--default, .cancel-button{
  border-radius: 20px;
  height: 35px;
  background-color: #909399;
  color: #f4f4f5;
}
.el-message-box__btns .el-button--primary,.confirm-button{
  border-radius: 20px;
  height: 35px;
  background-color: #5b8bff;
  color: #f4f4f5;
}
.el-message-box__title{
  color: #5b8bff;
  font-size: 22px;
  margin-bottom:-10px ;
}
.search-input{
  margin-bottom:-20px;
  display:flex;
}
.search-input .el-input__icon {
  margin-top: -7px !important; 
}
#account-search-border {
  border-radius: 25px;  
  height: 25px;
}
.account-search{
  width: 210px; 
  margin-left:20px;
}
.account-search-icon{
  font-size:15px; 
  margin:6px 4px; 
  color:#5b8bff;
}
.add-button{
  width:150px;
  background:#5b8bff; 
  color:#f4f4f5; 
  border-radius: 340px;
  height: 25px; 
  padding-top:4px;
  position: absolute;
  right: 80px;
}
.change-page{
  margin-top:15px
}
.el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf {
  border-bottom:none;
  text-align:center;
}
.el-table th.el-table__cell.is-leaf{
  color: #7986a6;
  font-weight: 500;
}
.el-table td.el-table__cell{
  padding:3px 0;
}
.el-upload{
  display: inline;
  float: left;
}
</style>
